package org.mclll.xwangplugin.questTracking.questGoal;

import me.pikamug.quests.events.quester.BukkitQuesterPostUpdateObjectiveEvent;
import me.pikamug.quests.quests.components.BukkitObjective;
import me.pikamug.quests.quests.components.Stage;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.npc.NPCRegistry;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.scoreboard.Objective;
import org.jetbrains.annotations.NotNull;
import org.mclll.xwangplugin.questTracking.persistence.Persistence;

import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

/**
 * @author: geduo
 * @date: 2023/10/13 14:23
 */
public class TalkToNpcQuestTrack {
    private static final String LINE_FORMAT = "与%s对话";

    public static void questTracking(Objective context, Integer line, Stage questsStage) {
        LinkedList<UUID> npcToInteract = questsStage.getNpcsToInteract();
        NPCRegistry npcRegistry = CitizensAPI.getNPCRegistry();
        if (npcToInteract.isEmpty() || npcRegistry == null) {
            return;
        }
        for (UUID uuid : npcToInteract) {
            context.getScore(getGoalFormat(CitizensAPI.getNPCRegistry().getByUniqueIdGlobal(uuid).getName())).setScore(line--);
        }
    }

    @NotNull
    public static String getGoalFormat(String npcName) {
        return ChatColor.YELLOW + String.format(LINE_FORMAT, npcName);
    }

    @NotNull
    public static String getFinishFormat(String npcName) {
        return ChatColor.GRAY + String.format(LINE_FORMAT, npcName) + " (✓)";
    }

    public static void goalFinish(BukkitQuesterPostUpdateObjectiveEvent event, List<Persistence.SerializeScore> scoreboard) {
        BukkitObjective questsObj = (BukkitObjective) event.getObjective();
        UUID npcUuid = (UUID) questsObj.getGoalObject();
        NPCRegistry npcRegistry = CitizensAPI.getNPCRegistry();
        if (npcRegistry == null) {
            return;
        }
        String npcName = CitizensAPI.getNPCRegistry().getByUniqueIdGlobal(npcUuid).getName();
        String finishFormat = getFinishFormat(npcName);
        String goalFormat = getGoalFormat(npcName);
        for (Persistence.SerializeScore serializeScore : scoreboard) {
            if (serializeScore.getName().equals(goalFormat)) {
                serializeScore.setName(finishFormat);
                serializeScore.setValue(scoreboard.get(scoreboard.size() - 1).getValue() - 1);
                break;
            }
        }
    }


}
